﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Columns;
using DevExpress.XtraTreeList.Nodes;

using QLTV.Database;
using DevExpress.XtraGrid.Views.Grid;
using QLTV.Database.dsUsersTableAdapters;
using QLTV.Forms.BaoMat;

namespace QLTV
{

    public partial class frmPhanQuyen : BaseForm
    {
        public frmPhanQuyen()
        {
            InitializeComponent();
            _activedEvent += frmPhanQuyen__activedEvent;

        }
        private void frmPhanQuyen__activedEvent()
        {
            bindTreeUser(false);
        }

        private void checkPermission()
        {
            cmdLuu.Enabled = MyPermission.Sua;
            btnSua.Enabled = MyPermission.Sua;
            btnThem.Enabled = MyPermission.Sua;
            treeQuyen.OptionsBehavior.Editable = MyPermission.Sua;
            //Quyen xuat
            cmdXuat.Enabled = MyPermission.Xuat;
        }


        private void frmPhanQuyen_Load(object sender, EventArgs e)
        {
            checkPermission();
            bindTreeUser(false);
        }
        private void bindTreeUser(Boolean loadByRole)
        {
            treeUser.ClearNodes();
            if (loadByRole)
            {

                string userName = "";
                string RoleName = "";
                int roleID;


                using (tblRoleTableAdapter tadRole = new tblRoleTableAdapter())
                {
                    Database.dsUsers.tblRoleDataTable dtRole = new dsUsers.tblRoleDataTable();
                    Database.dsUsers.tblUsersDataTable dtUser = new dsUsers.tblUsersDataTable();

                    dtRole = tadRole.GetData();
                    for (int i = 0; i < dtRole.Rows.Count; i++)
                    {
                        RoleName = dtRole.Rows[i]["cTenRole"].ToString();
                        roleID = Convert.ToInt16(dtRole.Rows[i]["iRoleid"]);
                        TreeListNode parentNode = treeUser.AppendNode(null, null);
                        parentNode.SetValue("User", RoleName);
                        parentNode.StateImageIndex = 2;
                        //Add child
                        using (tblUsersTableAdapter tadUser = new tblUsersTableAdapter())
                        {
                            dtUser = tadUser.GetDataByRoleID(roleID);
                            for (int j = 0; j < dtUser.Rows.Count; j++)
                            {
                                userName = dtUser.Rows[j]["cUserName"].ToString();
                                TreeListNode childNode = treeUser.AppendNode(null, parentNode);
                                childNode.SetValue("User", userName);
                                childNode.StateImageIndex = 0;
                            }

                        }

                    }

                }
            }
            else
            {
                string userName = "";
                string tenPhong = "";
                int idPhong;

                using (tblPhongTableAdapter tadPhong = new tblPhongTableAdapter())
                {
                    Database.dsUsers.tblPhongDataTable dtPhong = new dsUsers.tblPhongDataTable();
                    Database.dsUsers.tblUsersDataTable dtUser = new dsUsers.tblUsersDataTable();

                    dtPhong = tadPhong.GetData();
                    for (int i = 0; i < dtPhong.Rows.Count; i++)
                    {
                        tenPhong = dtPhong.Rows[i]["cTenPhong"].ToString();
                        idPhong = Convert.ToInt16(dtPhong.Rows[i]["iPhongId"]);
                        TreeListNode parentNode = treeUser.AppendNode(null, null);
                        parentNode.SetValue("User", tenPhong);
                        parentNode.StateImageIndex = 1;
                        //Add child
                        using (tblUsersTableAdapter tadUser = new tblUsersTableAdapter())
                        {
                            dtUser = tadUser.GetDataByPhongID(idPhong);
                            for (int j = 0; j < dtUser.Rows.Count; j++)
                            {
                                userName = dtUser.Rows[j]["cUserName"].ToString();
                                if (userName != UserName)
                                {
                                    TreeListNode childNode = treeUser.AppendNode(null, parentNode);
                                    childNode.SetValue("User", userName);
                                    childNode.StateImageIndex = 0;
                                }
                            }

                        }

                    }

                }
            }
            treeUser.ExpandAll();
            if (treeUser.Nodes.Count > 0 && treeUser.FocusedNode.HasChildren)
                treeUser.FocusedNode.FirstNode.Selected = true;
        }
        private void radUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedValue = radUser.Properties.Items[radUser.SelectedIndex].Value.ToString();
            if (selectedValue.ToLower() == "byphong")
            {
                bindTreeUser(false);
            }
            else
            {
                bindTreeUser(true);
            }
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Forms.BaoMat.frmUser f = new Forms.BaoMat.frmUser();
            f.isNew = true;
            f.ShowDialog();
            loadTree();

        }
        private void loadTree()
        {
            treeUser.ClearNodes();
            bindTreeUser(false);
            //string selectedValue = radUser.Properties.Items[radUser.SelectedIndex].Value.ToString();

            //if (selectedValue.ToLower() == "byphong")
            //{
            //    treeUser.ClearNodes();
            //    bindTreeUser(false);
            //}
            //else
            //{
            //    bindTreeUser(true);
            //}
        }

        private void treeUser_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            if (treeUser.Nodes.Count > 0)
                if (!(e.Node.Level == 0))
                {
                    this.tblQuyenTableAdapter.FillByUserName(this.dsUsers.tblQuyen, e.Node.GetDisplayText(columnUser));
                    treeQuyen.ExpandAll();
                }
                else if (e.Node.HasChildren)
                {
                    this.tblQuyenTableAdapter.FillByUserName(this.dsUsers.tblQuyen, e.Node.Nodes[0].GetDisplayText(columnUser));
                    treeQuyen.ExpandAll();
                }
        }

        private void barRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            loadTree();
        }

        private void barClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void treeQuyen_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {

        }

        private void treeQuyen_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {

            if (Convert.ToBoolean(e.Node.GetValue(colIsAdmin)) != true)
            {
                bool check = true;
                //uncheck parent if all child is false
                //foreach (TreeListNode _node in e.Node.ParentNode.Nodes)
                //{
                //    check = check || Convert.ToBoolean(_node.GetValue(e.Column));
                //}
                //if (!check)
                //    setPermission(e.Node.ParentNode, e.Column, false);
                //Set full permission
                if (e.Column == colbFull)
                {
                    if (checkParent(e.Node, colbFull))
                    {
                        setFull(e.Node, (Boolean)e.Value);
                    }
                    else
                    {
                        XtraMessageBox.Show("Chọn quyền không phù hợp", "Thông báo");
                    }
                }
                else // set specific permision
                {
                    if (checkParent(e.Node, e.Column))
                    {

                        if (e.Column != colbTruyCap)
                        {
                            setPermission(e.Node, e.Column, (Boolean)e.Value);
                            if ((Boolean)e.Value)
                                setPermission(e.Node, colbTruyCap, true);
                        }
                        else
                        {
                            if (!(Boolean)e.Value)
                            {
                                setPermission(e.Node, colbThem, false);
                                setPermission(e.Node, colbSua, false);
                                setPermission(e.Node, colbXoa, false);
                                setPermission(e.Node, colbIn, false);
                                setPermission(e.Node, colbXuat, false);
                                setPermission(e.Node, colbNhap, false);
                            }
                            setPermission(e.Node, e.Column, (Boolean)e.Value);
                        }
                        //uncheck Full permision

                        foreach (TreeListColumn item in treeQuyen.Columns)
                        {
                            if (item.Visible == true && item.ReadOnly == false && item != colbFull)
                            {
                                check = check && Convert.ToBoolean(e.Node.GetValue(item));
                            }
                        }
                        if (check)
                            setPermission(e.Node, colbFull, true);
                        else
                            setPermission(e.Node, colbFull, false);
                                             
                    }
                    else
                    {

                        MessageBox.Show(rm.GetString("sSelectPermisionErr", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo));
                    }
                }

            }
            else
                XtraMessageBox.Show(rm.GetString("sIsAdmin", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OK);
        }

        private void setPermission(TreeListNode node, object colid, Boolean value)
        {
            node.SetValue(colid, value);
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                setPermission(node.Nodes[i], colid, value);

            }

        }
        private Boolean checkParent(TreeListNode node, object colid)
        {
            if (node != null)
            {

                if (node.ParentNode != null)
                    return (Boolean)node.ParentNode.GetValue(colid);
                else
                    return true;
            }
            return false;

        }
        private void setFull(TreeListNode node, Boolean value)
        {

            node.SetValue("bFull", value);
            node.SetValue("bTruyCap", value);
            node.SetValue("bThem", value);
            node.SetValue("bSua", value);
            node.SetValue("bXoa", value);
            node.SetValue("bIn", value);
            node.SetValue("bNhap", value);
            node.SetValue("bXuat", value);
            for (int i = 0; i < node.Nodes.Count; i++)
            {

                setFull(node.Nodes[i], value);
            }


        }

        private void cmdLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                tblQuyenBindingSource.EndEdit();
                tblQuyenTableAdapter.Update(dsUsers.tblQuyen);
                //    this.tblQuyenTableAdapter.FillByUserName(this.dsUsers.tblQuyen, treeUser.FocusedNode.GetDisplayText(columnUser));

                XtraMessageBox.Show(rm.GetString("sMessageSuccess", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Error:  " + ex.Message, rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OK);
            }

        }

        private void barEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmUser f = new frmUser();
            f.StartPosition = FormStartPosition.CenterParent;
            f.username = treeUser.FocusedNode.GetDisplayText(columnUser);
            f.isNew = false;
            f.ShowDialog();
        }

        private void treeQuyen_ShowingEditor(object sender, CancelEventArgs e)
        {

            //if (Convert.ToBoolean(treeQuyen.FocusedNode.GetValue(colIsAdmin)) != true)
            //{
            //    if (treeQuyen.FocusedColumn.FieldName == "bFull")
            //    {
            //        if (checkParent(treeQuyen.FocusedNode, colbFull))
            //        {
            //            setFull(treeQuyen.FocusedNode, b);

            //        }
            //        else
            //        {
            //            e.Cancel = true;
            //        }



            //    }

            //}
            //else
            //    XtraMessageBox.Show("Không được thay đổi tài khoản này", "Cảnh báo", MessageBoxButtons.OK);
        }

        private void treeQuyen_ShownEditor(object sender, EventArgs e)
        {

        }

        private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
            {
                if (!treeUser.FocusedNode.HasChildren)
                {
                    tblUsersTableAdapter tadUser = new tblUsersTableAdapter();
                    tadUser.Delete(treeUser.FocusedNode.GetValue("User").ToString());
                    bindTreeUser(false);

                }
            }

        }





    }
}
